Skip to content

[parkhojeong] WEEK 07 Solutions - #2795

Open
parkhojeong wants to merge 10 commits into
DaleStudy:mainfrom
parkhojeong:week7
Open

[parkhojeong] WEEK 07 Solutions#2795
parkhojeong wants to merge 10 commits into
DaleStudy:mainfrom
parkhojeong:week7

Conversation

@parkhojeong

@parkhojeong parkhojeong commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

답안 제출 문제

작성자 체크 리스트

  • Projects의 오른쪽 버튼(▼)을 눌러 확장한 뒤, Week를 현재 주차로 설정해주세요.
  • 문제를 모두 푸시면 프로젝트에서 StatusIn Review로 설정해주세요.
  • 코드 검토자 1분 이상으로부터 승인을 받으셨다면 PR을 병합해주세요.

검토자 체크 리스트

Important

본인 답안 제출 뿐만 아니라 다른 분 PR 하나 이상을 반드시 검토를 해주셔야 합니다!

  • 바로 이전에 올라온 PR에 본인을 코드 리뷰어로 추가해주세요.
  • 본인이 검토해야하는 PR의 답안 코드에 피드백을 주세요.
  • 토요일 전까지 PR을 병합할 수 있도록 승인해주세요.

@dalestudy

dalestudy Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

📊 parkhojeong 님의 학습 현황

이번 주 제출 문제

문제 난이도 유형 분석
longest-substring-without-repeating-characters Medium ✅ 의도한 유형
number-of-islands Medium ✅ 의도한 유형
reverse-linked-list Easy ✅ 의도한 유형
set-matrix-zeroes Medium ✅ 의도한 유형
unique-paths Medium ✅ 의도한 유형

누적 학습 요약

  • 풀이한 문제: 30 / 75개
  • 이번 주 유형 일치율: 100% (5문제 중 5문제 일치)

문제 풀이 현황

카테고리 진행도 완료
Array ■■■■■■□ 8 / 10 (Medium 5, Easy 3)
Dynamic Programming ■■■■□□□ 7 / 11 (Easy 1, Medium 6)
Matrix ■■■■□□□ 2 / 4 (Medium 2)
String ■■■■□□□ 5 / 10 (Medium 2, Easy 3)
Heap ■■□□□□□ 1 / 3 (Medium 1)
Tree ■■□□□□□ 4 / 14 (Medium 3, Easy 1)
Binary ■□□□□□□ 1 / 5 (Easy 1)
Linked List ■□□□□□□ 1 / 6 (Easy 1)
Graph ■□□□□□□ 1 / 8 (Medium 1)
Interval □□□□□□□ 0 / 5 ← 아직 시작 안 함

🤖 이 댓글은 GitHub App을 통해 자동으로 작성되었습니다.

🔢 API 사용량 (gpt-5-nano)
요청 입력 토큰 출력 토큰 합계 비용
1 1,990 222 2,212 $0.000188
2 1,889 212 2,101 $0.000179
3 1,891 203 2,094 $0.000176
4 1,779 226 2,005 $0.000179
5 1,767 236 2,003 $0.000183
합계 9,316 1,099 10,415 $0.000905

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

  • 패턴: Hash Map / Hash Set, Sliding Window
  • 설명: 문자열에서 중복 문자를 관리하기 위해 해시 맵으로 문자 위치를 추적하고, 시작 인덱스를 점차 이동시키는 방식으로 부분문자열 길이를 최대화한다. 이는 슬라이딩 윈도우 패턴의 대표적인 구현이다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n)
Space O(min(n, k))

피드백: 문자 인덱스 저장소를 사용해 각 문자 마지막 위치를 추적하고, 중복이 등장하면 시작 인덱스를 갱신한다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

  • 패턴: Depth-First Search, Backtracking
  • 설명: 섬의 방문 여부를 재귀적으로 탐색하며 연결된 '1'을 방문 처리하는 DFS 패턴이 사용됩니다. 각 섬의 시작점에서 연결된 모든 노드를 방문해서 카운트하는 방식으로 문제를 풀이합니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(rows * cols)
Space O(rows * cols)

피드백: 그리드의 모든 원소를 한 번씩 방문하고, 섬의 연결 요소를 DFS로 탐색한다.

개선 제안: 재귀 깊이가 큰 입력에 대비해 비재귀 DFS나 BFS로 구현해 스택 오버플로를 피하는 방법을 고려해볼 수 있습니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

  • 패턴: Two Pointers, Linked List
  • 설명: 주어진 코드는 단일 연결 리스트를 역순으로 뒤집기 위해 두 포인터(prev, cur)를 사용합니다. 한 노드를 순회하며 연결 방향을 바꿔 가며 진행하는 대표적 패턴입니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n)
Space O(1)

피드백: 선행 노드 정보를 임시 저장하고 포인터를 차례로 뒤집어간다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

  • 패턴: Depth-First Search, Greedy, Hash Map / Hash Set
  • 설명: 코드가 DFS로 각 방향으로 탐색하며 0인 위치를 마커로 표시한 뒤, 마지막에 다시 0으로 복원합니다. 인접한 0의 위치를 표시하는 방식은 탐색 패턴과 플래그 마킹의 조합으로 보이며, 간단한 마커를 사용한 탐색 기법이 드러납니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(m*n)
Space O(1)

피드백: 두 단계로 나눠 제로를 확산시키는 방식으로 in-place 해결을 시도했다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

  • 패턴: Dynamic Programming, Greedy, Hash Map / Hash Set
  • 설명: 특정 칸의 경로 수를 위쪽과 왼쪽 칸의 수의 합으로 계산하는 DP 방식으로 해를 구합니다. 겹치는 부분 문제를 해결하며 그리드 순회로 결과를 채웁니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(m*n)
Space O(m*n)

피드백: 왼쪽 위에서 오른쪽 아래로 경로의 수를 누적 합으로 구한다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이거 재귀때문에 공간복잡도 O(max(m, n)) 일텐데 패턴분석이 이상하게 되어 있네요
훨씬 간단한 공간복잡도 O(1) 풀이도 있어요!

@alphaorderly alphaorderly Aug 5, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        maze = [[1] * n for _ in range(m)]

        for i in range(1, m):
            for j in range(1, n):
                maze[i][j] = maze[i - 1][j] + maze[i][j - 1]

        return maze[m - 1][n - 1]

칸 채운다고 생각하시면 복잡한 if 없이도 충분히 가능하세요!

그리고

  1. 공간복잡도 O(n)
  2. 공간복잡도 O(1)

인 풀이도 있으니까 해보시면 좋을것 같네요

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O(1)으로도 풀어보겠습니다. 감사합니다.

Comment thread unique-paths/parkhojeong.py Outdated
Comment on lines +3 to +4
row = [0] * m
grid = [row] * n

@alphaorderly alphaorderly Aug 5, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 부분을 이렇게 만드시면 동일한 row 객체의 레퍼런스가 행의 개수만큼 반복됩니다. 따라서 한 행의 열 값을 변경하면 다른 모든 행의 값도 함께 바뀌는 대참사가 일어날 수 있어요.

예를 들면 아래 코드는:

a = [0] * 5
b = [a] * 5

a[1] = 1

print(*b, sep="\n")

다음과 같이 모든 행의 두 번째 값이 함께 변경됩니다.

[0, 1, 0, 0, 0]
[0, 1, 0, 0, 0]
[0, 1, 0, 0, 0]
[0, 1, 0, 0, 0]
[0, 1, 0, 0, 0]

각 행을 독립적인 리스트로 만들려면 리스트 컴프리헨션을 사용하는 것이 안전합니다.

grid = [[0] * m for _ in range(n)]

다만 현재 풀이가 정상적으로 작동한 원리는 1차원 DP를 활용하는 방식과 정확히 동일합니다. 따라서 여기서 공간 복잡도를 최적화하는 아이디어도 자연스럽게 떠올리실 수 있을 것 같아요!

@parkhojeong parkhojeong Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

짚어주셔서 감사합니다. 가끔씩 실수하는 부분인데 우연히 통과됐네요. 한 칼럼씩 계산하는 방식으로 풀이 업데이트 해보았습니다.

Comment thread reverse-linked-list/parkhojeong.py Outdated
prev, cur = None, head

while cur:
next = cur.next

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

next는 파이썬 내장 함수랑 이름이 겹쳐서 ( 아마 leetcode에서도 색상으로 다르게 보이실거에요 )
사용을 자제하시는게 어떠실까 싶습니다.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

감사합니다. 다른 이름으로 변경 해주었습니다.

Comment thread set-matrix-zeroes/parkhojeong.py Outdated
if matrix[row][col] == 0:
return

matrix[row][col] = MARKER

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

파이썬이라 가능하다지만, 정수 행렬에 문자열을 넣는것은 좀 별로이지 않을까 싶습니다.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

같은 타입 중 입력 값 범위에 해당하지 않는 sys.maxsize 쓰도록 변경했습니다.

@alphaorderly alphaorderly Aug 5, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        if len(s) == 0:
            return 0

        ch_to_idx = {}
        start_idx = 0

        i = 0
        length_of_longest_substring = 1

        for i, ch in enumerate(s):
            if ch in ch_to_idx and ch_to_idx[ch] >= start_idx:
                start_idx = ch_to_idx[ch] + 1

            ch_to_idx[ch] = i
            length_of_longest_substring = max(i - start_idx + 1, length_of_longest_substring)


        return length_of_longest_substring

제 생각엔 ans를 구하는것을 따로 분리해서 분기에 공통로직이 많은것 보다는 이렇게

경우를 크게 따지지 않고 전부 하는게 가독성이 좋지 않을까 라는 의견이 있습니다.

2개의 항목을 가지는 max 함수는 O(1)의 시간복잡도를 가지기 때문에 O(N) 루프 안에 돌려도 큰 성능상 문제가 없을것으로 보여서요

@JeonJe
JeonJe self-requested a review August 5, 2026 12:11

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

longest-substring-without-repeating-characters/parkhojeong.py
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        if s == "":
            return 0

        ch_to_idx = {}
        start_idx = 0

        i = 0
        length_of_longest_substring = 1
        for i in range(len(s)):
            ch = s[i]
            if ch in ch_to_idx and ch_to_idx[ch] >= start_idx:
                start_idx = ch_to_idx[ch] + 1
                ch_to_idx[ch] = i
            else:
                ch_to_idx[ch] = i
                length_of_substring = i - start_idx + 1
                length_of_longest_substring = max(length_of_longest_substring, length_of_substring)

        return length_of_longest_substring
  • 패턴: Hash Map / Hash Set, Sliding Window
  • 설명: 문자열 부분문자열의 길이를 구하기 위해 현재 창의 시작 지점을 이동시키며 각 문자 위치를 해시맵으로 추적하는 방식으로, 창의 크기를 연속적으로 조정하는 Sliding Window와 해시맵을 이용한 중복 문자 관리가 핵심 패턴입니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n)
Space O(min(n, σ))

피드백: 해시맵으로 마지막 등장 인덱스를 추적하고 윈도우 시작점을 중복 문자의 이전 위치로 갱신한다. 그러나 length_of_longest_substring 초기값과 부분 문자열 길이 계산 로직에서 혼선이 있어 실행 중 일부 경우에 잘못될 수 있다.

개선 제안: 초기값과 길이 계산 로직을 명확히 하여 모든 경우에 올바르게 동작하도록 수정하면 안정적이다. 예를 들어 length_of_substring 변수를 항상 i - start_idx + 1로 계산하고, 새로운 중복 발견 시 start_idx를 업데이트한 뒤 최장 길이를 반영.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

number-of-islands/parkhojeong.py
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        row_len = len(grid)
        col_len = len(grid[0])

        def dfs(row: int, col: int):
            if not (0 <= row < row_len and 0 <= col < col_len):
                return

            if grid[row][col] == "0":
                return

            grid[row][col] = "0"
            dfs(row - 1, col)
            dfs(row + 1, col)
            dfs(row, col - 1)
            dfs(row, col + 1)

        num_islands = 0
        for row in range(row_len):
            for col in range(col_len):
                if grid[row][col] == "1":
                    num_islands += 1
                    dfs(row, col)

        return num_islands
  • 패턴: DFS
  • 설명: DFS를 이용해 인접한 땅('1')을 방문 처리하며 섬의 수를 세는 방식으로 구현되어 있습니다. 재귀를 통해 상하좌우로 연결된 영역을 탐색합니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(rows * cols)
Space O(rows * cols)

피드백: 전형적인 DFS 기반 섬 탐색으로 모든 셀을 한 번씩 방문한다. 재귀 깊이가 크게 증가하면 스택 오버플로 가능성이 있다.

개선 제안: 재귀 대신 명시적 스택을 사용한 DFS나 BFS로 구현하면 스택 깊이 문제를 피할 수 있다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

reverse-linked-list/parkhojeong.py
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        prev_node, cur_node = None, head

        while cur_node:
            next_node = cur_node.next

            cur_node.next = prev_node
            prev_node, cur_node = cur_node, next_node

        return prev_node
  • 패턴: Two Pointers, Linked List
  • 설명: head 포인터와 prev 포인터를 사용해 리스트를 역순으로 순회하며 링크를 뒤집는 전형적인 패턴으로, 두 포인터를 활용한 순서 반전(Reverse) 작업이다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n)
Space O(1)

피드백: 추가 데이터 구조 없이 링크를 뒤집어 나가는 표준 방법이다.

개선 제안: 특별한 개선 필요 없으며 현재 구현이 적절해 보인다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

set-matrix-zeroes/parkhojeong.py
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """

        row_len = len(matrix)
        col_len = len(matrix[0])
        MARKER = "#"

        def dfs(row, col, d_row, d_col):
            if not (0 <= row < row_len and 0 <= col < col_len):
                return 

            if matrix[row][col] == 0:
                return

            matrix[row][col] = MARKER
            dfs(row + d_row, col + d_col, d_row, d_col)

        for row in range(row_len):
            for col in range(col_len):
                if matrix[row][col] == 0:

                    matrix[row][col] = MARKER
                    dfs(row + 1, col, 1, 0)
                    dfs(row - 1, col, -1, 0)
                    dfs(row, col + 1, 0, 1)
                    dfs(row, col - 1, 0, -1)

        for row in range(row_len):
            for col in range(col_len):
                if matrix[row][col] == MARKER:
                    matrix[row][col] = 0
  • 패턴: Depth-First Search, Greedy
  • 설명: 코드는 각 0인 원소를 중심으로 인접한 비제로 값을 MARKER로 표시하며 DFS로 연결 경로를 탐색해 0으로 처리하는 방식으로 작동합니다. 전체적으로는 연결 탐색과 표식 후 재처리의 흐름이므로 DFS와 간단한 표식 전략이 핵심 패턴입니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(rows * cols)
Space O(rows * cols)

피드백: 현재 구현은 마커로 DFS를 활용해 연쇄적으로 0으로 바꾸는 비효율적 구조를 보인다. 여러 방향으로 확산시키는 DFS가 필요 이상으로 중복 방문을 유발할 수 있다.

개선 제안: 표준 접근인 첫 통과에서 행/열 배열에 플래그를 남겨 두고, 후처리에서 0으로 바꾸는 방식으로 구현하면 간단하고 명확하다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

unique-paths/parkhojeong.py
class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        column = [1] * m

        for col in range(n - 1):

            for row in range(1, m):
                column[row] = column[row] + column[row - 1]

        return column[-1]
  • 패턴: Dynamic Programming, Greedy
  • 설명: 2차원 격자에서의 경로 수를 열과 행의 합으로 갱신하는 DP 아이디어로, 메모리 절약을 위해 1차원 배열을 활용하는 패턴입니다. 경로의 합 규칙을 이용한 점화식의 전형적 예시입니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(m * n)
Space O(m)

피드백: 1차원 DP 배열로 메모리 사용을 최소화한 점은 좋다.

개선 제안: 명확성을 위해 주석으로 점화식을 추가하면 이해도가 상승한다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

set-matrix-zeroes/parkhojeong.py
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """

        row_len = len(matrix)
        col_len = len(matrix[0])
        MARKER = sys.maxsize

        def dfs(row, col, d_row, d_col):
            if not (0 <= row < row_len and 0 <= col < col_len):
                return

            if matrix[row][col] == 0:
                return

            matrix[row][col] = MARKER
            dfs(row + d_row, col + d_col, d_row, d_col)

        for row in range(row_len):
            for col in range(col_len):
                if matrix[row][col] == 0:

                    matrix[row][col] = MARKER
                    dfs(row + 1, col, 1, 0)
                    dfs(row - 1, col, -1, 0)
                    dfs(row, col + 1, 0, 1)
                    dfs(row, col - 1, 0, -1)

        for row in range(row_len):
            for col in range(col_len):
                if matrix[row][col] == MARKER:
                    matrix[row][col] = 0
  • 패턴: Depth-First Search, Backtracking
  • 설명: 코드가 각 0인 위치를 기준으로 상하좌우로 탐색하며 인접 원소를 표시하는 DFS 흐름을 사용하고, 표시된 값을 나중에 0으로 되돌리는 방식이 Backtracking 성격과 DFS 패턴을 함께 보입니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n*m)
Space O(n*m)

피드백: 0이 있는 위치를 기준으로 인접 방향으로 탐색해 MARKER를 거쳐 간접적으로 표시한다. 하지만 모든 0을 찾고 마커 처리까지 가능하므로 총 시간은 이중 루프로 결정되고 공간은 추가 배열 없이 마커를 사용해 구현한다.

개선 제안: 현재 구현은 in-place 처리가 가능하나, O(1) 추가 공간으로 구현하려면 행/열 마커를 따로 두지 않고 첫 줄에서 처리 여부를 추적하는 방식으로 개선할 수 있습니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

set-matrix-zeroes/parkhojeong.py
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """

        row_len = len(matrix)
        col_len = len(matrix[0])

        zero_row_set = set()
        zero_col_set = set()

        for r in range(row_len):
            for c in range(col_len):
                if matrix[r][c] == 0:
                    zero_row_set.add(r)
                    zero_col_set.add(c)

        for r in zero_row_set:
            for c in range(col_len):
                matrix[r][c] = 0

        for c in zero_col_set:
            for r in range(row_len):
                matrix[r][c] = 0
  • 패턴: Greedy, Hash Map / Hash Set, Two Pointers, Sliding Window, Dynamic Programming, Binary Search, Monotonic Stack, Heap / Priority Queue, BFS, DFS, Backtracking, Divide and Conquer, Union Find, Trie, Bit Manipulation
  • 설명: 주어진 코드는 0인 위치를 추적하기 위해 행과 열의 인덱스를 집합에 저장하고, 이후 해당 행과 열을 제일 많이 0으로 만드는 방식으로 행과 열을 0으로 바꿉니다. 공간 절약을 위해 추가 배열 대신 집합으로 표시하는 패턴이 핵심입니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(R * C)
Space O(R + C)

피드백: 두 개의 추가 집합으로 모든 0의 위치를 기록한 뒤, 해당 행과 열을 순회하며 0으로 설정한다. 공간복잡도는 저장된 행/열의 수에 의존한다.

개선 제안: 고려해볼 만한 대안: 입력 행/열을 직접 플래그로 표시하는 인-플레이스 방식이나, 첫 행/열을 사용해 추가 공간 없이 O(1) 공간으로 구현하는 방법을 탐색해볼 수 있다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

@parkhojeong parkhojeong moved this from Solving to In Review in 리트코드 스터디 8기 Aug 7, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

set-matrix-zeroes/parkhojeong.py
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """

        row_len = len(matrix)
        col_len = len(matrix[0])

        zero_row_set = set()
        zero_col_set = set()

        for r in range(row_len):
            for c in range(col_len):
                if matrix[r][c] == 0:
                    zero_row_set.add(r)
                    zero_col_set.add(c)

        for r in range(row_len):
            for c in range(col_len):
                if r in zero_row_set or c in zero_col_set:
                    matrix[r][c] = 0
  • 패턴: Hash Map / Hash Set, Greedy
  • 설명: 0인 위치를 기록해 두고, 해당 행 또는 열의 원소를 0으로 바꾸는 방식으로 문제를 해결합니다. 해시 세트를 사용해 행과 열의 영향을 추적하는 점이 특징입니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(R * C)
Space O(R + C)

피드백: 두 개의 추가 집합을 사용해 모든 0의 위치를 기록한 후 이중 루프로 다시 지나며 행/열에 속하는 원소를 0으로 바꾼다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: In Review

Development

Successfully merging this pull request may close these issues.

2 participants